package com.lening.common.util;

import cn.hutool.extra.spring.SpringUtil;

import com.lening.common.login.LoginUser;
import com.lening.common.properties.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author 牛强
 * @datetime 2024/4/22 14:14
 * @description 类对象
 */
public final class JwtUtil {
    //配置信息
    public static JwtProperties PROPERTIES = SpringUtil.getBean(JwtProperties.class);

    //加密的Key
    private static SecretKey SECRET_KEY = Keys.hmacShaKeyFor(PROPERTIES.getSecret().getBytes());

    /**
     * 获取 HttpServletRequest
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return Objects.requireNonNull(attributes).getRequest();
    }

    /**
     * 获取 token 无参
     *
     * @return
     */
    public static String getToken() {
        String token = getRequest().getHeader(PROPERTIES.getHeader());
        return getRequest().getHeader(PROPERTIES.getHeader());
    }

    /**
     * 获取token 有参
     *
     * @param request
     * @return
     */
    public static String getToken(HttpServletRequest request) {
        return request.getHeader(PROPERTIES.getHeader());
    }

    /**
     * 生成 token
     * @param user
     * @return
     */
    public static String createToken(LoginUser user) {
        return Jwts.builder().header()//头部信息
                .add("alg", "HS256")
                .add("typ", "JWT")
                .and()
                .claims(ConvertUtil.toMap(user))//添加载荷信息
                .signWith(SECRET_KEY)//签名
                .compact(); //拼接

    }

    /**
     * 根据token 获取载荷信息
     *
     * @param token
     * @return
     */
    public static Claims parseToken(String token) {
        return Jwts.parser().verifyWith(SECRET_KEY).build().parseSignedClaims(token).getPayload();
    }

    /**
     * 从 token 获取当前登录的用户 -有参
     *
     * @param token
     * @return
     */
    public static LoginUser getCurrentUser(String token) {
        Claims claims = parseToken(token);
        LoginUser user = new LoginUser();
        user.setUserId(claims.get("userId", Long.class));
//        user.setRoleId(claims.get("roleId", Long.class));
//        user.setTenantId(claims.get("tenantId", Long.class));
        user.setUsername(claims.get("username", String.class));
        return user;
    }

    /**
     * 获取当前登录用户的信息-无参
     *
     * @return
     */
    public static LoginUser getCurrentUser() {
        return getCurrentUser(getToken());
    }

}
